<?php
namespace App\Http\Controllers\Supplier;
use App\Models\NewAdmin;
use App\Models\Order;
use App\Models\OrderLog;
use App\Models\ShopUser;
use App\Services\AuthService;
use App\Services\CommonService;
use App\Services\OrderService;
use Illuminate\Http\Request;
class StatisticsController extends BaseController
{
    public function orderCheckData(Request $request){
        $orderCreateTime = $request->input('orderCreateTime', '');
        $pageSize = $request->input('pageSize',10);
        $page = $request->input('page',1);
        $where= [
            ['admin.is_delete',CommonService::IS_DELETE_NOT],
            ['admin.type',AuthService::MODEL_MERCHANT],
            ['admin.user_id',$this->users['user_id']],
        ];
        $adminUser = NewAdmin::from('sp_other_admin as admin')
            ->where($where)
            ->leftjoin('sp_other_auth_group as group','admin.role_id','=','group.id')
            ->select('admin.id','admin.mobile','admin.username','admin.create_time','admin.status','admin.type','admin.user_id','admin.role_id','group.title','group.rules')
            ->orderBy('admin.id','desc')
            ->paginate($pageSize);
        $adminUser = $adminUser?$adminUser->toArray():[];
        $wherea=[];
        foreach ($adminUser['data'] as $key=>$user){
            $adminUser['data'][$key]['pass_number']=(new OrderLog)->getCountNumber($user['id'],$orderCreateTime);
            $adminUser['data'][$key]['check_number']=(new OrderLog)->getCheckDataNumber($user['id'],$orderCreateTime);
            $adminUser['data'][$key]['return_number']=$adminUser['data'][$key]['check_number']-$adminUser['data'][$key]['pass_number'];
            $adminUser['data'][$key]['admin_name'] = $this->shopUser['shopname'];
            if ($orderCreateTime) {
                $orderCreateTimea = explode('~', $orderCreateTime);
                $wherea[] = ['o.create_time', '>=', strtotime($orderCreateTimea[0])];
                $wherea[] = ['o.create_time', '<=',strtotime($orderCreateTimea[1])];
            }
            if ($orderCreateTime) {
                $orderCreateTimeb = explode('~', $orderCreateTime);
                $whereb[] = ['o.create_time', '>=', $orderCreateTimeb[0]];
                $whereb[] = ['o.create_time', '<=', $orderCreateTimeb[1]];
            }
            $adminUser['data'][$key]['not_check_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_log as log', 'o.id', 'log.order_id')
                ->where('log.status',OrderLOG::ORDER_LOG_PROCESS)
                ->where('o.status',OrderService::ORDER_STATUS_SIGN_NOCHECK)
                ->distinct('log.order_id')
                ->where($whereb)
                ->where('log.user_id',$user['id'])
                ->count();
            $adminUser['data'][$key]['not_pay_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_SIGN_NOTPAY)
                ->distinct('re.order_id')
                ->where($wherea)
                ->where('re.uid',$user['id'])
                ->count();
            $adminUser['data'][$key]['pay_success_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_PAY_SUCCESS)
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['deliver_success_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_DELIVER_SUCCESS)
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['goods_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_CONFIRM_GOODS)
                ->where('re.uid',$user['id'])
                ->distinct('re.order_id')
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['completed_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_COMPLETED)
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['cancel_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_CENCEL)
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['repayment_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_REPAYMENT)
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['overdue_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_OVERDUE)
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();
            $adminUser['data'][$key]['refund_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->whereIn('o.status',OrderService::getOrderStatus('orderRefund'))
                ->distinct('re.order_id')
                ->where('re.uid',$user['id'])
                ->where($wherea)
                ->count();


        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$adminUser);

    }

    //个人数据详情
    public function orderCheckDataDetail(Request $request){

        $orderCreateTime = $request->input('orderCreateTime', '');
        $id= $request->input('id',0);
        $user_id= $request->input('user_id',0);
        if($orderCreateTime){
            $orderCreateTimea = explode('~', $orderCreateTime);
            $days = new \DatePeriod(
                new \DateTime($orderCreateTimea[0]),
                new \DateInterval('P1D'),
                new \DateTime($orderCreateTimea[1])
            );
        }else{
            $days = new \DatePeriod(
                new \DateTime(date('Y-m-d',strtotime('-1 week'))),
                new \DateInterval('P1D'),
                new \DateTime(date('Y-m-d',time()))
            );
        }

        $data=[];
        foreach ($days as $key=>$today){
            $orderCreateTime=$today->format('Y-m-d').'~'.$today->format('Y-m-d').' 23-59-59';
            $day=$today->format('Y-m-d');
            $wherea=[];
            $whereb=[];
            $data[$key]['day']=$today->format('Y-m-d');
            $data[$key]['pass_number']=(new OrderLog)->getCountNumber($id,$orderCreateTime);
            $data[$key]['check_number']=(new OrderLog)->getCheckDataNumber($id,$orderCreateTime);
            $data[$key]['return_number']=$data[$key]['check_number']-$data[$key]['pass_number'];
            $data[$key]['admin_name'] = $this->shopUser['shopname'];
            $wherea[] = ['o.create_time', '>=', strtotime($day)];
            $wherea[] = ['o.create_time', '<=',strtotime($day)+86400];

            $whereb[] = ['log.create_time', '>=', strtotime($day)];
            $whereb[] = ['log.create_time', '<=', strtotime($day)+86400];

            $data[$key]['not_check_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_log as log', 'o.id', 'log.order_id')
                ->where('log.status',OrderLog::ORDER_LOG_PROCESS)
                ->where('o.status',OrderService::ORDER_STATUS_SIGN_NOCHECK)
                ->distinct('log.order_id')
                ->where($whereb)
                ->where('log.user_id',$id)
                ->count();

            $data[$key]['not_pay_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_SIGN_NOTPAY)
                ->distinct('re.order_id')
                ->where($wherea)
                ->where('re.uid',$id)
                ->count();

            $data[$key]['pay_success_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_PAY_SUCCESS)
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
            $data[$key]['deliver_success_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_DELIVER_SUCCESS)
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
            $data[$key]['goods_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_CONFIRM_GOODS)
                ->where('re.uid',$id)
                ->distinct('re.order_id')
                ->where($wherea)
                ->count();
            $data[$key]['completed_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_COMPLETED)
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
            $data[$key]['cancel_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_CENCEL)
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
            $data[$key]['repayment_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_REPAYMENT)
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
            $data[$key]['overdue_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->where('o.status',OrderService::ORDER_STATUS_OVERDUE)
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
            $data[$key]['refund_number'] = Order::from('sp_order_2 as o')
                ->leftjoin('sp_order_remark_2 as re', 're.order_id', 'o.id')
                ->leftjoin('sp_order_log as log', 're.order_id', 'log.order_id')
                ->whereRaw('re.uid=log.user_id')
                ->where('content','订单审核通过')
                ->whereIn('o.status',OrderService::getOrderStatus('orderRefund'))
                ->distinct('re.order_id')
                ->where('re.uid',$id)
                ->where($wherea)
                ->count();
        }
        rsort($data);
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',$data);
    }

    public function checkData($type='week'){
        $data=[];
        $adminUser = NewAdmin::from('sp_other_admin as admin')
            ->leftjoin('sp_other_auth_group as group','admin.role_id','=','group.id')
            ->select('admin.id','admin.mobile','admin.username','admin.create_time','admin.status','admin.type','admin.user_id','admin.role_id','group.title','group.rules')
            ->orderBy('admin.create_time','desc')
            ->get();
        $adminUser = $adminUser?$adminUser->toArray():[];

       switch($type){
           case'week':
               $date=$this->tradeDays(7);
               $series=[];
               $username=[];
               foreach ($adminUser as $key=>$user){
                   $series['username']=$user['username'];
                   $username[$key][]=$user['username'];
                   foreach ($date as $ra){
                       $series[$key]['passData']=(new OrderLog)->getCount($user['id'],$ra);
                       $series[$key]['cheackData']=(new OrderLog)->getCheckData($user['id'],$ra);

                   }
               }
          break;
           case'month':
               $date=$this->tradeDays(30);
               $series=[];
               $username=[];
               foreach ($adminUser as $key=>$user){
                   $series['username']=$user['username'];
                   $username[$key][]=$user['username'];
                   foreach ($date as $ra){
                       $series[$key]['passData']=(new OrderLog)->getCount($user['id'],$ra);
                       $series[$key]['cheackData']=(new OrderLog)->getCheckData($user['id'],$ra);

                   }
               }
               break;
           case'threeMonth':
               $date=$this->tradeDays(90);
               $series=[];
               $username=[];
               foreach ($adminUser as $key=>$user){
                   $series['username']=$user['username'];
                   $username[$key][]=$user['username'];
                   foreach ($date as $ra){
                       $series[$key]['passData']=(new OrderLog)->getCount($user['id'],$ra);
                       $series[$key]['cheackData']=(new OrderLog)->getCheckData($user['id'],$ra);

                   }
               }
               break;
           case'sixMonth':
               $date=$this->tradeDays(180);
               $series=[];
               $username=[];
               foreach ($adminUser as $key=>$user){
                   $series['username']=$user['username'];
                   $username[$key][]=$user['username'];
                   foreach ($date as $ra){
                       $series[$key]['passData']=(new OrderLog)->getCount($user['id'],$ra);
                       $series[$key]['cheackData']=(new OrderLog)->getCheckData($user['id'],$ra);

                   }
               }
               break;
           case'year':
               $date=$this->tradeDays(365);
               $series=[];
               $username=[];
               foreach ($adminUser as $key=>$user){
                   $series['username']=$user['username'];
                   $username[$key][]=$user['username'];
                   foreach ($date as $ra){
                       $series[$key]['passData']=(new OrderLog)->getCount($user['id'],$ra);
                       $series[$key]['cheackData']=(new OrderLog)->getCheckData($user['id'],$ra);
                   }
               }
               break;
           default:
              $this->tradeDays(7);
       }

     return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,compact('date','series','username'));

    }

    //获取最近日期
    public function tradeDays($days=7){
        // 获取当前周几
        $date = [];
        for ($i = 0; $i < $days; $i++) {
            $date[] = date('Y-m-d', strtotime('-' . $i . ' days'));
        }
        return array_reverse($date);
    }

    /**
     * 数据概览
     * @param $id
     * @return false|string
     */
    public function dataOverview(){
        if($this->users['user_id']=='1704471738'){
            $where2 = ['o.seller_id' => $this->users['user_id']];

            $totalAmount['should_rent'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->where($where2)
                ->whereIn('o.status',OrderService::getOrderStatus(OrderService::ORDER_SETTLE_CONFIRM_STATUS))
                ->where('ol.begin_time','<', time())
                ->select('ol.rent')
                ->sum('ol.rent');

            $totalAmount['returned_rent'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->leftjoin('sp_order_lease_2 as ol', 'o.id', 'ol.order_id')
                ->whereIn('o.status',OrderService::getOrderStatus(OrderService::ORDER_SETTLE_CONFIRM_STATUS))
                ->where($where2)
                ->where('ol.status', 1)
                ->select('ol.rent')
                ->where('ol.begin_time','<',time())
                ->sum('ol.rent');

            //到期应还订单数
            $totalAmount['should_orders'] = Order::from('sp_order_2 as o')
                ->where($where2)
                ->whereIn('o.status',array_merge(OrderService::getOrderStatus(OrderService::ORDER_LIST_STATUS_RETURN),['10','20','30','60','38','39']))
                ->count();

            //到期已还订单数
            $totalAmount['returned_orders'] = Order::from('sp_order_2 as o', 'o.id', 'ol.order_id')
                ->where($where2)
                ->whereIn('o.status',array_merge(OrderService::getOrderStatus(OrderService::ORDER_LIST_STATUS_RETURN),['10','20','30','60']))
                ->count();


        }
        return ReturnMsg(CommonService::HTTP_CODE_SUCCESS,'获取成功',compact('totalAmount'));
    }
}
